package com.barbeque.mall.controller.wx;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.barbeque.mall.bean.BaseRespVo;
import com.barbeque.mall.bean.system.MarketStorage;
import com.barbeque.mall.bean.system.vo.StorageCreateVO;
import com.barbeque.mall.service.SysStorageService;
import com.barbeque.mall.util.Constant;
import com.barbeque.mall.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * @author Tezel
 * @since 2022/07/18 16:49
 */
@RestController
@RequestMapping("wx/storage")
public class WxStorageController {
    @Autowired
    SysStorageService sysStorageService;

    @RequestMapping("upload")
    public BaseRespVo storageCreateVO(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        String accessKeyId = Constant.ACCESS_KEY_ID;
        String accessKeySecret = Constant.ACCESS_KEY_SECRET;
        String bucket = "cskaoyan";
        String endPoint = "oss-cn-beijing.aliyuncs.com";

        //获取文件大小
        long size = file.getSize();

        //获取当前时间
        Date date = new Date(System.currentTimeMillis());

        //给文件一个随机名
        String name = file.getOriginalFilename();
        String[] split = name.split("\\.");
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + split[split.length - 1];

        //文件上传的阿里云
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        InputStream myFile = file.getInputStream();
        PutObjectResult putObjectResult = ossClient.putObject(bucket, fileName, myFile);

        //获取图片的url = https://bucket.endPonit/文件名
        String fileUrl = Constant.DOMAIN_NAME + fileName;

        //生成文件的唯一索引，将文件名进行md5散列得到
        String key = MD5Utils.getMd5(fileName);


        //开始封装对象
        MarketStorage marketStorage = new MarketStorage();

        marketStorage.setKey(key);
        marketStorage.setName(fileName);
        marketStorage.setType(split[split.length - 1]);
        marketStorage.setSize((int) size);
        marketStorage.setUrl(fileUrl);
        marketStorage.setAddTime(date);
        marketStorage.setUpdateTime(date);

        int i = sysStorageService.CreateStorage(marketStorage);

        StorageCreateVO storageCreateVO = new StorageCreateVO();

        // BeanUtils.copyProperties(marketStorage,storageCreateVO);

        if (i == 1) {
            return BaseRespVo.ok(marketStorage);
        }
        return BaseRespVo.invalidData("图片上传失败");

    }
}
